<template>
  <div>
    <div class="w-screen h-screen flex">
      <div class="flex-none w-64 flex flex-col h-full">
        <div class="border-b flex-none h-12 px-3 flex items-center justify-center">
          <router-link to="/" class="flex-1 flex items-center">
            <div class="text-sm">返回</div>
          </router-link>
          <router-link to="/article">
            <el-button size="mini" type="text" round><i class="el-icon-plus"></i>新增</el-button>
          </router-link>
        </div>
        <div class="flex-1 overflow-y-auto overflow-x-hidden h-0">
          <el-input
              class="input-b-border"
              placeholder="请输入关键字"
              v-model="params.keyword">
            <i @click="onSearch()" slot="suffix" class="el-input__icon el-icon-search cursor-pointer"></i>
          </el-input>
          <div
              v-for="(item, index) in list"
              :key="index"
              :class="form.id === item.id ? 'item-active':''"
              class="flex items-center justify-between px-3 border-b cursor-pointer">
            <router-link class="flex-1 truncate py-3 text-sm" :to="'/article/'+item.id">
              {{ item.title }}
            </router-link>
            <div class="px-2">
              <el-dropdown trigger="click">
                <i class="el-icon-more"></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <a :href="'https://www.lufuhu.com/articles/'+item.id" target="_blank">查看</a>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="clickDel(item)">删除</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
        <div class="h-12 flex-none">
          <el-pagination
              class="mt-2"
              :background="true"
              :hide-on-single-page="true"
              layout="prev, pager, next"
              :current-page="params.page"
              :total="total"
              :page-size="per_page"
              @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
      <div
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(225, 225, 225, 0.8)"
          class="flex-1 flex flex-col w-full h-full">
        <div class="flex-none flex items-end h-12">
          <el-input v-model="form.title" class="input-b-border" placeholder="标题"></el-input>
          <el-button class="mx-1" size="small" type="primary" @click="showDialog()">保存</el-button>
        </div>
        <div class="flex-1">
          <iframe
              class="w-full h-full"
              ref="editormd"
              src="https://www.lufuhu.com/tools/editor.md/index.html"
              frameborder="no"
              border="0"
              marginwidth="0"
              marginheight="0"
              scrolling="no"
              allowtransparency="yes">
          </iframe>
        </div>
      </div>
    </div>
    <el-dialog
        title="其他"
        :visible.sync="dialogVisible"
        width="60vh">
      <el-form ref="form" size="small" :model="form" label-width="50px">
        <el-form-item label="标签">
          <el-select
              class="w-full"
              v-model="form.tag"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择">
            <el-option
                v-for="(item, index) in enumTag"
                :key="index"
                :label="item"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5}"
              placeholder="请输入内容"
              v-model="form.summary">
          </el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              class="avatar-uploader"
              action="/api/v1/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
            <img v-if="form.pic" :src="form.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="开启">
          <el-switch @change="switchChange" v-model="status"></el-switch>
        </el-form-item>
        <el-form-item class="ml-2" label="排序">
          <el-input-number v-model="form.sort" :min="0" :max="100"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapActions, mapGetters} from "vuex";

export default {
  name: "editArticle",
  data() {
    return {
      form: {
        id: '',
        title: "",
        pic: "",
        tag: [],
        sort: 0,
        content: "",
        summary: "",
        status: 1,
      },
      status: true,
      enumStatus: {},
      enumTag: [],
      edIframeWin: {},
      isIframeOnload: false,
      isDetailsData: false,
      dialogVisible: false,
      list: [],
      current_page: 0,
      per_page: 0,
      total: 0,
      params: {
        page: 1,
      },
      loading: false,
    }
  },
  watch: {
    articleGetTags: function (val) {
      this.enumTag = val.data
    },
    articleViewData: function (val) {
      this.form = val.data;
      this.status = val.data.status === 1;
      this.isDetailsData = true;
      this.setContent();
      this.loading = false
    },
    articleAddData: function (val) {
      this.onSaveSuccess(val.data)
    },
    articleEditData: function (val) {
      this.onSaveSuccess(val.data)
    },
    articleListData: function (val) {
      this.list = val.data.data
      this.per_page = val.data.per_page
      this.total = val.data.total
    },
    articleDelData: function () {
      this.$message({
        type: 'success',
        message: '删除成功!'
      });
      this.articleList(this.params);
    },
    $route() {
      this.getDetails();
    }
  },
  mounted() {
    this.edIframeWin = this.$refs.editormd.contentWindow;
    this.articleTags();
    this.articleList(this.params);
    this.getDetails();
    let that = this;
    window.addEventListener("message", function (event) {
      let data = event.data;
      switch (data.method) {
        case 'onLoad': //初始化完成
          that.isIframeOnload = true;
          that.setContent();
          break;
        case 'onChange': //内容改变事件
          that.form.content = data.content;
          break;
      }
    }, false);
  },
  methods: {
    ...mapActions([
      'articleTags',
      'articleView',
      'articleList',
      'articleAdd',
      'articleEdit',
      'articleDel'
    ]),
    switchChange(val) {
      this.form.status = val ? 1 : 0;
    },
    onSearch() {
      this.params.page = 1;
      this.articleList(this.params)
    },
    paginationChange(page) {
      this.params.page = page;
      this.articleList(this.params)
    },
    showDialog() {
      this.dialogVisible = true;
    },
    getDetails() {
      this.loading = false;
      if (this.$route.params.id) {
        this.form.id = this.$route.params.id;
        this.loading = true;
        this.articleView({id: this.form.id});
      } else {
        this.form = this.$options.data().form;
        this.setContent();
      }
    },
    onSubmit() {
      if (this.form.id) {
        this.articleEdit(this.form);
      } else {
        this.articleAdd(this.form);
      }
    },
    onSaveSuccess(val) {
      this.$message({
        type: 'success',
        message: '保存成功!'
      });
      this.dialogVisible = false;
      this.articleList(this.params);
      if (val) {
        this.$router.push('/article/' + val)
      }
    },
    setContent() {
      if (this.isDetailsData && this.isIframeOnload) {
        this.edIframeWin.postMessage({
          method: 'setContent',
          content: this.form.content
        }, "*");
      }
    },
    clickDel(item) {
      this.$confirm("是否删除此文章（" + item.title + "）", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.articleDel({id: item.id});
        if (parseInt(this.$route.params.id) === item.id) {
          this.$router.push('/article');
        }
      });
    },
    handleAvatarSuccess(res) {
      this.form.pic = res.data;
    },
  },
  computed: {
    ...mapGetters([
      'articleTagsData',
      'articleViewData',
      'articleListData',
      'articleAddData',
      'articleEditData',
      'articleDelData'
    ])
  }
}
</script>

<style scoped>
.item-active {
  background-color: #f2f7fa;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>